<template>
    <div class="users-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <User />
                        </el-icon>
                        <span>用户管理</span>
                    </div>
                    <div class="search-box">
                        <el-input v-model="searchQuery" placeholder="请输入昵称搜索" clearable @clear="handleSearch"
                            @keyup.enter="handleSearch">
                            <template #suffix>
                                <el-icon class="search-icon" @click="handleSearch">
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>
                    </div>
                </div>
            </template>

            <el-table :data="userList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="id" label="ID" />
                <el-table-column prop="avatar" label="头像">
                    <template #default="{ row }">
                        <el-avatar :size="40" :src="row.avatar">
                            {{ row.nickname?.charAt(0)?.toUpperCase() }}
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="age" label="年龄" align="center">
                    <template #default="{ row }">
                        {{ row.age || '未设置' }}
                    </template>
                </el-table-column>
                <el-table-column prop="gender" label="性别" align="center">
                    <template #default="{ row }">
                        {{ row.gender === null ? '未设置' : getGenderLabel(row.gender) }}
                    </template>
                </el-table-column>
                <el-table-column prop="state" label="状态" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.state" :active-value="1" :inactive-value="0"
                            @change="(val) => handleStateChange(row, val)" />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="注册时间" align="center">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[8, 10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const userList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 获取用户列表
const getUserList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/user/list',
            method: 'get',
            params: {
                page: currentPage.value,
                size: pageSize.value,
                nickname: searchQuery.value
            }
        })
        userList.value = res.data.records
        total.value = res.data.total
        console.log(userList.value)
    } catch (error) {
        console.error('获取用户列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 获取性别标签
const getGenderLabel = (gender) => {
    const genderMap = {
        0: '未知',
        1: '男',
        2: '女'
    }
    return genderMap[gender] || '未知'
}

// 切换用户状态
const handleStateChange = async (row, value) => {
    try {
        await request({
            url: `/user/state/${row.id}`,
            method: 'put',
            data: { state: value }
        })
        ElMessage.success('状态更新成功')
    } catch (error) {
        row.state = value === 1 ? 0 : 1 // 恢复状态
        console.error('状态更新失败:', error)
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getUserList()
}

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val
    getUserList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getUserList()
}

onMounted(() => {
    getUserList()
})
</script>

<style scoped>
.users-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.search-box {
    width: 250px;
}

.search-icon {
    cursor: pointer;
    color: #606266;
}

.search-icon:hover {
    color: #409EFF;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

:deep(.el-avatar) {
    background: #409EFF;
}
</style>